import type { FC } from 'react'

type IProps = {
  addTodo: (content: string) => void
}

export const TodoHeader: FC<IProps> = (props) => {
  const onBlur = (e: any) => {
    if (!e.target.value || !e.target?.value?.trim()) {
      e.target.value = null
      return
    }
    props.addTodo(e.target.value)
    e.target.value = null
    e.target.focus()
  }
  const onKeyDown = (e: any) => {
    if (e.keyCode !== 13) return
    e.target.blur(e)
  }
  return (
    <header className="header">
      <h1>todos</h1>
      <input
        className="new-todo"
        placeholder="What needs to be done?"
        autoFocus
        onBlur={onBlur}
        onKeyDown={onKeyDown}
      />
    </header>
  )
}
